package org.nokatag.system;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.noka.gson.Gson;
import org.noka.gson.reflect.TypeToken;
import org.nokatag.dbgrid.CellParItem;
import org.nokatag.dbgrid.NDBGridDataItem;
import org.nokatag.dbgrid.NDBGridDataServer;
import org.nokatag.dbgrid.NDBOutFileImp;
import org.nokatag.dbgrid.NDBOutFileInterface;
import org.nokatag.password.AESPlus;


/**
 * 导出到excel
 * @author rebin
 *
 */
public class DataExcelOut extends NDBGridDataServer{
	
	public  void OutExcel(HttpServletRequest request,HttpServletResponse response,FilterConfig config){
		 try {
			 NDBGridDataItem da =sqlData(request);
			 List<CellParItem> cellName  = new ArrayList<CellParItem>();
			 String cells = request.getParameter("cells");
			 if(null!=cells){
				 Gson gson = new Gson();
				 cellName = gson.fromJson(cells, new TypeToken<List<CellParItem>>(){}.getType());
			 }
			 if(da==null)
				 return;
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			String filename=null;
			//-------------------汇总列与数据行合并------------------
			if(null!=da.getSumCells() && !da.getSumCells().isEmpty()){
				Map<String,String> sumap = da.getSumCells();
				Map<String,String> suList = new HashMap<String,String>();
				for(CellParItem m : cellName){
					String value = sumap.get(m.getName());
					if(null==value){
						suList.put(m.getName(), "");
					}else{
						suList.put(m.getName(), value);
					}
				}
				da.getRows().add(suList);
			}
			//-------------------下载-------------------------------
			String type = request.getParameter("typ");//类型
			filename = request.getParameter("fname");//文件名称
			String userOutFile = request.getParameter("oufile");//自定义导出类
			filename=getDefultFileName(filename,type);
			//-----------------自定义导出接口-----------------------
			if(userOutFile!=null &&userOutFile.trim().length()>1){
				List<String> outCellName = new ArrayList<String>();
				for(CellParItem m : cellName){
					outCellName.add(m.getCellname());
				}
				userOutFile=AESPlus.decrypt(userOutFile,Concest.SQLKEY);//解密
				List<List<String>> row = new ArrayList<List<String>>();
				for(Map<String,String> ro:da.getRows()){
					List<String> rcell = new ArrayList<String>();
					for(CellParItem m : cellName){
						String cvalue = ro.get((null==m.getName()?m.getCellname():m.getName()));
						rcell.add((null==cvalue?"&nbsp;":cvalue));
					}
					row.add(rcell);
				}
				UserFileInterface(os,userOutFile,type,row,outCellName,request);
			}else{
				NDBOutFileImp nOutFile = new NDBOutFileImp();
				//-----------------系统默认接口------------------------
				List<List<String>> row = new ArrayList<List<String>>();
				List<String> outCellName = new ArrayList<String>();
				for(CellParItem m : cellName){
					outCellName.add(m.getCellname());
				}
				for(Map<String,String> ro:da.getRows()){
					List<String> rcell = new ArrayList<String>();
					for(CellParItem m : cellName){
						String cvalue = ro.get((null==m.getName()?m.getCellname():m.getName()));
						rcell.add((null==cvalue?"":cvalue));
					}
					row.add(rcell);
				}
				if(type!=null && "csv".equals(type)){
					nOutFile.outCsvFile(os,row,outCellName,request);//生成csv
				}else if("pdf".equals(type)){
					nOutFile.outPDFFile(os,row,outCellName,request);//生成pdf
				}else{
					nOutFile.outExcelFile(os,row,outCellName,request);//生成excel
				}
			}
			//-----------下载文件---------------------------------------------------------
			if(filename!=null){
				SmartUpload su = new SmartUpload();
				su.initialize(config, request, response);
				if("pdf".equals(type)){
					su.setContentDisposition("");
					su.downloadFileByte(os.toByteArray(),filename,"application/pdf");//pdf直接打开
				}else{
					su.setContentDisposition(null);
					su.downloadFileByte(os.toByteArray(),filename);
				}
			}
		} catch (Exception e1) {
			BugInfoWrint.Print(e1);
		}
	}
	/**
	 * 用户自定义文件生成接口
	 */
	protected void  UserFileInterface(ByteArrayOutputStream os,String classPath,String type,List<List<String>> row,List<String> cellName,HttpServletRequest request) {
		try {
			NLoadFun nloadfun = new NLoadFun();
			NDBOutFileInterface action = (NDBOutFileInterface)nloadfun.getBean(classPath);
			
			if("csv".equals(type)){
				action.outCsvFile(os, row, cellName, request);
			}else if("pdf".equals(type)){
				action.outPDFFile(os, row, cellName, request);
			}else{
				action.outExcelFile(os, row, cellName, request);
			}
		} catch (Exception e) {
			BugInfoWrint.Print("noka connection is : " + "file:"+ Concest.ROOTDIR + "/WEB-INF/classes" + " " + classPath);
		}
	}
	//-------------------获取默认文件名---------------------------------
	private String getDefultFileName(String filename,String type){
		if(filename!=null){
			filename=AESPlus.decrypt(filename,Concest.SQLKEY);//解密 aaaaa$[yyyy-MM-dd]
			if(filename.indexOf("$[")!=-1 && filename.indexOf("]")!=-1){
				String ft = filename.substring(filename.indexOf("$[")+2,filename.indexOf("]"));
				SimpleDateFormat fd=new SimpleDateFormat(ft);
				String fdstr = fd.format(new Date());
				filename=filename.replace("$["+ft+"]", fdstr);
			}
		}
		if("csv".equals(type)){
			return (filename==null?System.currentTimeMillis()+".csv":filename+".csv");
		}else if("pdf".equals(type)){
			return (filename==null?System.currentTimeMillis()+".pdf":filename+".pdf");
		}else{
			return (filename==null?System.currentTimeMillis()+".xls":filename+".xls");
		}
	}
}
